L.ui.view.extend({
	repeater: L.rpc.declare({
		object: 'luci2',
		method: 'repeater'
	}),
	
	read_ap: function(s) {
		var self = this;
		
		L.file.read('/tmp/ap_scan').then(function(r) {
			L.ui.loading(false);
			var apList = $.parseJSON(r).list;
			
			var apTable = new L.ui.table({
				caption: L.tr('AP List'),
				columns: [{
					caption: L.tr('SSID'),
					key:     'ssid'
				}, {
					caption: L.tr('BSSID'),
					key:     'bssid'
				}, {
					caption: L.tr('Encryption'),
					key:     'security'
				}]
			});
			
			var form = $('<div />');
			apTable.rows(apList);
			apTable.insertInto(form);
			
			form.find('tr').click(function() {
				var ap = apList[$(this).index() - 1];
				var sid = s.getUCISections()[0]['.name'];
				var id = s.fields['ApCliSsid'].id(s.getUCISections()[0]['.name']);
				
				L.ui.dialog(false);
				
				$('#' + id).val(ap.ssid);
			});
			
			L.ui.dialog(L.tr('Please select the AP you want to relay'), form, {
				style:'confirm'
			});
		});
	},
	
	execute: function() {
		var self = this;
		
		var m = new L.cbi.Map('repeater', {
			caption:	L.tr('WiFi Repeater'),
			description:	L.tr('You can directly enter the SSID and password directly connected to the AP you want to relay, or scan the surrounding AP by scanning the AP function below, and then select the AP that you want to connect to.')
		});
		
		var s = m.section(L.cbi.TypedSection, 'main', {
			caption:	L.tr('Configuration')
		});
		
		s.option(L.cbi.CheckboxValue, 'ApCliEnable', {
			caption:	L.tr('Enabled')
		});
			
		s.option(L.cbi.InputValue, 'ApCliSsid', {
			caption:	L.tr('SSID')
		}).depends('ApCliEnable');
		
		s.option(L.cbi.PasswordValue, 'ApCliWPAPSK', {
			caption:	L.tr('Passphrase'),
			optional:	true,
			datatype:	'wpakey'
		}).depends('ApCliEnable');
		
		s.option(L.cbi.ButtonValue, '_scan', {
			text: L.tr('Scan'),
			caption: L.tr('Scan'),
			description: L.tr('Click to Scan the surrounding AP.')
		}).depends('ApCliEnable').on('click', function(e) {
			L.ui.loading(true, L.tr('Scanning, please wait for 5s...'));
			L.file.exec('ap_client', [ '-s', 'ra0', '-d', '-o', '/tmp/ap_scan', '-j' ]).then(function(r) {
				setTimeout(function() {
					self.read_ap(s);
				}, 6000);
			});
		});
		
		m.on('apply', function() {
			self.repeater();
		});
		
		return m.insertInto('#map');
	}
});
